﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../core/controllers/ring_controller.dart';
import '../../../services/ring_service.dart';
import '../../../gen/assets.gen.dart';

/// 蓝牙扫描页面
/// 用于扫描和连接戒指设备
class BluetoothScanView extends StatefulWidget {
  const BluetoothScanView({super.key});

  @override
  State<BluetoothScanView> createState() => _BluetoothScanViewState();
}

class _BluetoothScanViewState extends State<BluetoothScanView>
    with WidgetsBindingObserver {
  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  @override
  void initState() {
    super.initState();
    // 添加生命周期监听器
    WidgetsBinding.instance.addObserver(this);
    // 页面打开时自动开始扫描
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ringController.scanDevices();
    });
  }

  @override
  void dispose() {
    // 移除生命周期监听器
    WidgetsBinding.instance.removeObserver(this);
    // 页面关闭时停止扫描
    ringController.stopScan();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台返回前台时（例如从权限对话框返回），重新开始扫描
    if (state == AppLifecycleState.resumed) {
      print('🔄 [蓝牙扫描] 应用恢复，重新开始扫描');
      // 先停止当前扫描，然后重新开始
      ringController.stopScan();
      Future.delayed(const Duration(milliseconds: 500), () {
        ringController.scanDevices();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          '选择您的戒指',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Get.back(),
        ),
      ),
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(20.w),
          child: Column(
            children: [
              // 提示信息
              _buildTipSection(),
              
              SizedBox(height: 24.h),
              
              // 设备列表
              Expanded(child: _buildDeviceList()),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建提示信息区域
  Widget _buildTipSection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.orange.withOpacity(0.2),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: Colors.orange.withOpacity(0.3),
          width: 1.w,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.orange,
            size: 24.sp,
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Text(
              '找不到戒指？尝试给戒指充电、重启蓝牙或确保已授予蓝牙权限',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.orange,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建设备列表
  Widget _buildDeviceList() {
    return Obx(() {
      // 获取所有扫描到的设备
      final allDevices = ringController.scannedDevices;
      
      // 过滤AZ戒指设备（名称包含AZ或为AZ ring开头）
      final devices = allDevices.where((device) {
        if (device.name.isEmpty) return false;
        final deviceName = device.name.toUpperCase();
        return deviceName.contains('AZ ring') || deviceName.startsWith('AZ RING');
      }).toList();
      
      // 调试日志
      print('📊 [蓝牙扫描] 总设备数: ${allDevices.length}, AZ设备数: ${devices.length}, 扫描状态: ${ringController.isScanning}');
      
      // 如果正在扫描且没有找到AZ设备，显示扫描状态
      if (ringController.isScanning && devices.isEmpty) {
        return _buildScanningState();
      }
      
      // 如果扫描完成但没有找到AZ设备，显示空状态
      if (devices.isEmpty) {
        return _buildEmptyState();
      }
      
      // 显示找到的AZ设备列表
      print('✅ [蓝牙扫描] 显示 ${devices.length} 个AZ设备');
      
      return ListView.builder(
        itemCount: devices.length,
        itemBuilder: (context, index) {
          final device = devices[index];
          return _buildDeviceListItem(device);
        },
      );
    });
  }

  /// 构建扫描中状态
  Widget _buildScanningState() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
        ),
        SizedBox(height: 24.h),
        Text(
          '正在搜索戒指设备...',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          '请确保戒指已开启',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          Icons.bluetooth_searching,
          size: 80.sp,
          color: Colors.grey[600],
        ),
        SizedBox(height: 24.h),
        Text(
          '未发现AZ ring设备',
          style: TextStyle(
            fontSize: 18.sp,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          '请确保设备已开启且在附近\n',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  /// 获取颜色名称
  String _getColorName(String? colorCode) {
    if (colorCode == null) return '未知颜色';
    switch (colorCode) {
      case '0':
        return '典雅黑';
      case '2':
        return '奢雅金';
      case '3':
        return '玫瑰金';
      default:
        return '未知颜色';
    }
  }

  /// 获取戒指图片
  AssetGenImage _getRingImage(String? colorCode) {
    if (colorCode == null) return Assets.profile.ringScanBlack;
    switch (colorCode) {
      case '0':
        return Assets.profile.ringScanBlack;
      case '2':
      case '3':
        return Assets.profile.ringScanGold;
      default:
        return Assets.profile.ringScanBlack;
    }
  }

  /// 构建设备列表项
  Widget _buildDeviceListItem(RingDevice device) {
    final colorName = _getColorName(device.deviceColor);
    final size = device.deviceSize ?? '未知';
    final ringImage = _getRingImage(device.deviceColor);

    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: Colors.grey[700]!,
          width: 1.w,
        ),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(12.r),
          onTap: () => _connectToDevice(device),
          child: Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                // 戒指图片
                Stack(
                  children: [
                     ClipRRect(
                        borderRadius: BorderRadius.circular(12.r),
                        child: ringImage.image(
                          width: 60.w,
                          height: 60.w,
                          fit: BoxFit.cover,
                        ),
                      
                    ),
                    // 充电标志
                    if (device.isCharging)
                      Positioned(
                        right: 0,
                        top: 0,
                        child: Container(
                          padding: EdgeInsets.all(4.w),
                          decoration: BoxDecoration(
                            color: Colors.green,
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: Colors.grey[800]!,
                              width: 2.w,
                            ),
                          ),
                          child: Icon(
                            Icons.bolt,
                            color: Colors.white,
                            size: 14.sp,
                          ),
                        ),
                      ),
                  ],
                ),
                SizedBox(width: 16.w),
                // 设备信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              device.name,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                          // 充电文字标识
                          if (device.isCharging)
                            Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 8.w,
                                vertical: 2.h,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.green.withValues(alpha: 0.2),
                                borderRadius: BorderRadius.circular(4.r),
                                border: Border.all(
                                  color: Colors.green,
                                  width: 1.w,
                                ),
                              ),
                              child: Text(
                                '充电中',
                                style: TextStyle(
                                  color: Colors.green,
                                  fontSize: 10.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                        ],
                      ),
                      SizedBox(height: 4.h),
                      Text(
                        '$colorName, 尺寸 $size',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(height: 2.h),
                      Text(
                        device.address,
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ),
                // 连接按钮
                Icon(
                  Icons.chevron_right,
                  color: Colors.grey[400],
                  size: 24.sp,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 连接到指定设备
  void _connectToDevice(RingDevice device) async {
    // 立即返回到个人页面
    Get.back();
    
    // 开始连接设备
    await ringController.connectDevice(device);
  }
}
